<template>
  <ContentCard>
    <template #header>
      <pageHeaderNew :title="title" :breadCrumb="breadCrumb" showBack>
      </pageHeaderNew>
    </template>
    <a-tabs show-add-button auto-switch>
      <a-tab-pane key="1" title="短信通知模板">
        <ConditionBox :margin-bottom="20" :margin-left="20" :margin-right="20">
          <template #left>
            <a-input-search
              @press-enter="search_1"
              @search="search_1"
              :style="{ width: '320px' }"
              placeholder="请输入模板名称"
              search-button
              v-model="keyWord"
            />
          </template>
          <template #right>
            <a-button @click="visible = true" type="primary">新增模板</a-button>
            <a-button type="outline" @click="del(null, 1)" status="danger"
              >批量删除</a-button
            >
          </template>
        </ConditionBox>
        <table-turn :table-data="tableData_1" ref="tableRef_1" :args="args">
          <a-table-column align="center" :width="80">
            <template #title> 序号 </template>
            <template #cell="{ rowIndex }">
              {{ rowIndex + 1 }}
            </template>
          </a-table-column>
          <a-table-column
            :width="200"
            dataIndex="name"
            align="center"
            title="模板名称"
          ></a-table-column>
          <a-table-column
            :width="200"
            dataIndex="remark"
            align="center"
            title="模板描述"
          ></a-table-column>
          <a-table-column title="是否启用" data-index="enable" :width="150">
            <template #cell="{ record: { enable } }">
              <a-tag
                class="enable"
                :color="
                  enable === 1 ? `rgb(var(--green-1))` : 'rgb(var(--danger-1))'
                "
                :style="{
                  color:
                    enable === 1
                      ? `rgb(var(--green-6))`
                      : 'rgb(var(--danger-6))',
                  '--enable':
                    enable === 1
                      ? `rgb(var(--green-6))`
                      : 'rgb(var(--danger-6))'
                }"
              >
                {{ enable === 1 ? '启用' : '停用' }}
              </a-tag>
            </template>
          </a-table-column>
          <a-table-column
            :width="200"
            align="center"
            dataIndex="required"
            title="设为默认"
          >
            <template #cell="{ record }">
              <a-switch
                @change="changeRequired(record.id, 1)"
                :checked-value="1"
                :unchecked-value="2"
                v-model="record.required"
              />
              <!-- {{ record.required === 2 ? '禁用' : '启用' }} -->
            </template>
          </a-table-column>
          <a-table-column
            title="操作"
            align="center"
            :width="100"
            fixed="right"
          >
            <template #cell="{ record }">
              <a-space :size="0">
                <a-tooltip content="预览">
                  <icon-eye
                    size="26"
                    @click="look(record, 1)"
                    style="color: #5085ff; cursor: pointer"
                  />
                </a-tooltip>
                <a-tooltip content="复制">
                  <IconFont
                    type="icon-fuzhi"
                    :size="26"
                    :style="{
                      cursor: 'pointer'
                    }"
                    @click="goCopy(record.id, 1)"
                  />
                </a-tooltip>
                <a-tooltip content="编辑">
                  <icon-font
                    type="icon-edit"
                    :size="26"
                    @click="goEdit_1(record.id)"
                    :style="{
                      cursor: 'pointer'
                    }"
                  />
                </a-tooltip>
                <a-tooltip content="删除" position="left">
                  <a-popconfirm
                    content="是否确认删除该条数据?"
                    @ok="del(record, 1)"
                  >
                    <icon-font
                      type="icon-delete"
                      :size="26"
                      :style="{
                        cursor: 'pointer'
                      }"
                    />
                  </a-popconfirm>
                </a-tooltip>
              </a-space>
            </template>
          </a-table-column>
        </table-turn>
      </a-tab-pane>
      <a-tab-pane key="2" title="邮件通知模板">
        <ConditionBox :margin-bottom="20" :margin-left="20" :margin-right="20">
          <template #left>
            <a-input-search
              @press-enter="search_2"
              @search="search_2"
              :style="{ width: '320px' }"
              placeholder="请输入模板名称"
              search-button
              v-model="keyWord"
            />
          </template>
          <template #right>
            <a-button @click="add" type="primary">新增模板</a-button>
            <a-button type="outline" @click="del(null, 2)" status="danger"
              >批量删除</a-button
            >
          </template>
        </ConditionBox>
        <table-turn :table-data="tableData_2" ref="tableRef_2" :args="args">
          <a-table-column align="center" :width="80">
            <template #title> 序号 </template>
            <template #cell="{ rowIndex }">
              {{ rowIndex + 1 }}
            </template>
          </a-table-column>
          <a-table-column
            :width="200"
            dataIndex="name"
            align="center"
            title="模板名称"
          ></a-table-column>
          <a-table-column
            :width="200"
            dataIndex="remark"
            align="center"
            title="模板描述"
          ></a-table-column>

          <a-table-column
            :width="200"
            align="center"
            dataIndex="enable"
            title="启用状态"
          >
            <template #cell="{ record: { enable } }">
              <a-tag
                class="enable"
                :color="
                  enable === 1 ? `rgb(var(--green-1))` : 'rgb(var(--danger-1))'
                "
                :style="{
                  color:
                    enable === 1
                      ? `rgb(var(--green-6))`
                      : 'rgb(var(--danger-6))',
                  '--enable':
                    enable === 1
                      ? `rgb(var(--green-6))`
                      : 'rgb(var(--danger-6))'
                }"
              >
                {{ enable === 1 ? '启用' : '停用' }}
              </a-tag>
            </template>
          </a-table-column>
          <a-table-column
            :width="200"
            align="center"
            dataIndex="required"
            title="设为默认"
          >
            <template #cell="{ record }">
              <a-switch
                @change="changeRequired(record.id, 2)"
                :checked-value="1"
                :unchecked-value="2"
                v-model="record.required"
              />
              <!-- {{ record.required === 2 ? '禁用' : '启用' }} -->
            </template>
          </a-table-column>
          <a-table-column
            title="操作"
            align="center"
            :width="120"
            fixed="right"
          >
            <template #cell="{ record }">
              <div>
                <a-tooltip content="预览">
                  <icon-eye
                    size="26"
                    @click="look(record, 2)"
                    style="color: #5085ff; cursor: pointer"
                  />
                </a-tooltip>
                <a-tooltip content="复制">
                  <IconFont
                    type="icon-fuzhi"
                    :size="26"
                    :style="{
                      cursor: 'pointer'
                    }"
                    @click="goCopy(record.id, 2)"
                  />
                </a-tooltip>
                <a-tooltip content="编辑">
                  <icon-font
                    type="icon-edit"
                    :size="26"
                    @click="goEdit_2(record.id)"
                    :style="{
                      cursor: 'pointer'
                    }"
                  />
                </a-tooltip>
                <a-tooltip content="删除" position="left">
                  <a-popconfirm
                    content="是否确认删除该条数据?"
                    @ok="del(record, 2)"
                  >
                    <icon-font
                      type="icon-delete"
                      :size="26"
                      :style="{
                        cursor: 'pointer'
                      }"
                    />
                  </a-popconfirm>
                </a-tooltip>
              </div>
            </template>
          </a-table-column>
        </table-turn>
      </a-tab-pane>
    </a-tabs>
  </ContentCard>
  <Modals v-model:visible="visible" :refreshFn="refresh_1" :old-data="data_1" />
  <noticeTemplates ref="notice" :data="data" :fn="refresh_2" />
  <!-- // 短信预览 -->
  <a-modal
    v-model:visible="look_1"
    :modal-style="{
      boxShadow: '0px 0px 10px rgba(0, 0, 0, .6)',
      borderRadius: '50px',
      width: '250px',
      position: 'relative',
      height: ' 550px'
    }"
    :body-style="{
      height: '100%'
    }"
    :footer="false"
    simple
  >
    <template #title>
      <div class="close" @click="look_1 = false" style="color: #c9bcbc">
        <icon-close size="30" />
      </div>
    </template>
    <div>
      <RichTextNew
        :disabled="true"
        v-model:content="lookData.data"
        :name="'ac'"
        ref="rich"
      ></RichTextNew>

      <div class="round"></div>
    </div>
  </a-modal>
  <!-- // 邮箱预览 -->
  <a-modal
    v-model:visible="look_2"
    :width="800"
    :body-style="{
      height: '100%',
      maxHeight: '600px !important'
    }"
  >
    <template #title> 入职通知邮件模板预览 </template>
    <div>
      <RichTextNew
        :disabled="true"
        v-model:content="lookData.data"
        :name="'acb'"
        ref="rich"
      ></RichTextNew>
    </div>
  </a-modal>
  <CopyModal
    v-model:visible="copyVisible"
    @copy-emit="copyEmit"
    @copyEditEmit="copyEditEmit"
    :validateFun="validateName"
  />
</template>

<script setup lang="ts">
import useExamineTabsStore from '@/store/modules/base/examineTabs/index';
import {
  GetBonboardingInform,
  DelBonboardingInform,
  GetBonboardingInformDetail,
  EditBonboardingInformDefault,
  AddBonboardingInform,
  RepeatSchemePeople
} from '@/apis/management/personnel/baseSetting/TransactionSetting';
import { validateRules } from '@/utils/common';
import {
  GetEntryScheme,
  GetEntrySchemeById
} from '@/apis/management/personnel/baseSetting/TransactionSetting';
import noticeTemplates from './noticeTemplate/index.vue';
import { Message, Modal } from '@arco-design/web-vue';
import { baseType } from './noticeTemplate/type';
import Modals from './Modals.vue';
import clonedeep from 'lodash.clonedeep';
import { GetBusinessModalData } from '@/apis/controltotal';

const notice = ref();
const title = '入职通知模板列表';
const breadCrumb: string[] = ['人事', '基础设置', '入职通知模板设置'];
const examineTabsStore = useExamineTabsStore();
const currTab = computed({
  get: () => examineTabsStore.tabsValue,
  set: (val: string) => {
    examineTabsStore.setTabs(val);
  }
});
// 表格配置
const args = {
  rowSelection: {
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false
  }
};
const keyWord = ref('');
const data = ref<any>({});
const data_1 = ref<baseType>({});
const look_1 = ref(false);
const look_2 = ref(false);

const selectedList1 = computed(() => tableRef_1.value.selectedList);
const selectedListData1 = computed(() => tableRef_1.value.selectedListData);
const selectedList2 = computed(() => tableRef_2.value.selectedList);
const selectedListData2 = computed(() => tableRef_2.value.selectedListData);

// 删除
const del = async (record: any, type: number) => {
  try {
    let selectedList = type === 1 ? selectedList1.value : selectedList2.value;
    let selectedListData =
      type === 1 ? selectedListData1.value : selectedListData2.value;
    if (type === 1) {
      if (!record) {
        if (selectedList.length === 0) {
          Message.error('请至少选择一项！');
        } else {
          Modal.confirm({
            title: '提示',
            content: '确定要删除选中的数据吗？',
            onOk: async () => {
              try {
                if (selectedListData.find((item: any) => item.required === 1)) {
                  Message.error('默认模板不能删除！');
                } else {
                  await DelBonboardingInform({
                    ids: selectedList
                  });
                  tableRef_1.value.selectedList = [];
                  refresh_1();
                }
              } catch (error: unknown) {
                console.log(error);
              }
            }
          });
        }
      } else {
        if (record.required === 1) Message.error('默认模板不能删除！');
        else {
          await DelBonboardingInform({
            ids: [record.id]
          });
          tableRef_1.value.selectedList = [];
          refresh_1();
        }
      }
    } else {
      if (!record) {
        if (selectedList.length === 0) {
          Message.error('请至少选择一项！');
        } else {
          Modal.confirm({
            title: '提示',
            content: '确定要删除选中的数据吗？',
            onOk: async () => {
              try {
                if (selectedListData.find((item: any) => item.required === 1)) {
                  Message.error('默认模板不能删除！');
                } else {
                  await DelBonboardingInform({
                    ids: selectedList
                  });
                  tableRef_2.value.selectedList = [];
                  refresh_2();
                }
              } catch (error: unknown) {
                console.log(error);
              }
            }
          });
        }
      } else {
        if (record.required === 1) Message.error('默认模板不能删除！');
        else {
          await DelBonboardingInform({
            ids: [record.id]
          });
          tableRef_2.value.selectedList = [];
          refresh_2();
        }
      }
    }
    // if (data.required === 1) {
    //   return Message.error('默认模板无法删除');
    // }
    // let selectedList = [];
    // if (type === 1) selectedList = selectedList1.value;
    // else selectedList = selectedList2.value;

    // await DelBonboardingInform({
    //   ids: selectedList.length > 0 ? selectedList : [data.id]
    // });
    // if (type === 1) refresh_1();
    // else refresh_2();
  } catch (error) {
    console.log(error);
  }
};
const tableRef_1 = ref();
const tableRef_2 = ref();
const requiredId_1 = ref();
const requiredId_2 = ref();

const tableData_1 = async (page: any) => {
  try {
    const res: any = await GetBonboardingInform({
      ...page,
      name: keyWord.value,
      type: 1
    });
    res.content?.forEach((ele: any) => {
      if (ele.required === 1) {
        requiredId_1.value = ele.id;
      }
    });

    return Promise.resolve(res);
  } catch (err: unknown) {
    console.log(err);
  }
};
const tableData_2 = async (page: any) => {
  try {
    const res: any = await GetBonboardingInform({
      ...page,
      name: keyWord.value,
      type: 2
    });
    res.content?.forEach((ele: any) => {
      if (ele.required === 1) {
        requiredId_2.value = ele.id;
      }
    });
    return Promise.resolve(res);
  } catch (err: unknown) {
    console.log(err);
  }
};

// 点击新增模板按钮
const add = () => {
  notice.value.fullScreen();
};
// 编辑
const goEdit_2 = async (id: number, name?: string) => {
  const res: any = await GetBonboardingInformDetail({ id });
  data_1.value = res;
  if (res?.detail[0]?.content) {
    let newcontent = res.detail[0].content;
    const componentModel: any = [];
    let oldcodeArray: any = [];
    // const res2: any = await GetEntryScheme({ required: 1 });
    // const data: any = await GetEntrySchemeById({
    //   id: res2.content[0].id
    // });

    const {
      funcCtlInfos: { children }
    } = (await GetBusinessModalData({
      funcCode: 'SER_FUNC65E1F1B346CF47BC952C91D24207EDC4'
    })) as any;
    const data = children;
    data.map((ele: any) => {
      componentModel.push(...ele.subDetail.subRelDetail);
    });
    const codeArray = res.detail[0].codeArray.split(',');
    oldcodeArray = componentModel.filter(
      (ele: any) => codeArray.indexOf(ele.ctlCode) !== -1
    );
    res.detail[0].oldcodeArray = oldcodeArray;
    oldcodeArray.forEach((ele: any) => {
      let regexp = new RegExp(`#${ele.ctlCode}#`, 'g');
      newcontent = newcontent.replace(regexp, `#${ele.ctlCnName}#`);
    });
    res.detail[0].content = newcontent;
  }
  currData.data = res;
  if (name) currData.data.name = name;

  data.value = clonedeep(res);
  notice.value.fullScreen();
};

let currData = reactive({
  data: {}
});
const goEdit_1 = async (id: number, name?: string) => {
  const res: any = clonedeep(await GetBonboardingInformDetail({ id }));
  let regexp = new RegExp(`#C62B8DC31189847E0972B5D8F721404B1#`, 'g');
  res.detail[0].content = res.detail[0].content.replace(regexp, `#姓名#`);
  if (name) {
    res.name = name;
    delete res.detail[0].id;
    delete res.id;
  }
  currData.data = clonedeep(res);
  data_1.value = res;
  visible.value = true;
};

const lookData: any = reactive({ data: {} });
// 预览
const look = async (oldData: any, type: number) => {
  if (type === 1) {
    const res: any = await GetBonboardingInformDetail({ id: oldData.id });
    let regexp = new RegExp(`#C62B8DC31189847E0972B5D8F721404B1#`, 'g');
    res.detail[0].content = res.detail[0].content.replace(regexp, `#姓名#`);
    lookData.data = res.detail[0].content;

    look_1.value = true;
  } else {
    const res: any = await GetBonboardingInformDetail({ id: oldData.id });
    let newcontent = res.detail[0].content;
    const componentModel: any = [];
    let oldcodeArray: any = [];
    const {
      funcCtlInfos: { children }
    } = (await GetBusinessModalData({
      funcCode: 'SER_FUNC65E1F1B346CF47BC952C91D24207EDC4'
    })) as any;
    const data = children;
    data.map((ele: any) => {
      componentModel.push(...ele.subDetail.subRelDetail);
    });
    const codeArray = res.detail[0].codeArray.split(',');
    oldcodeArray = componentModel.filter(
      (ele: any) => codeArray.indexOf(ele.ctlCode) !== -1
    );
    res.detail[0].oldcodeArray = oldcodeArray;
    oldcodeArray.forEach((ele: any) => {
      let regexp = new RegExp(`#${ele.ctlCode}#`, 'g');
      newcontent = newcontent.replace(regexp, `#${ele.ctlCnName}#`);
    });
    res.detail[0].content = newcontent;
    if (res.detail.length > 1) res.detail[0].content += '</br><p>入职材料</p>';
    res.detail?.forEach((ele: any, index: number) => {
      if (index) {
        res.detail[0].content += ele.stuffContent
          ? `<br/>${index}.${ele.stuffName}${'(' + ele.stuffContent + ')'}`
          : `<br/>${index}.${ele.stuffName}`;
      }
    });
    lookData.data = res.detail[0].content;
    look_2.value = true;
  }
  // visible.value = true;
};

let copyVisible = ref(false);
let currId = ref(0);
let currType = ref(1);
// 显示复制弹窗
const goCopy = (id: number, type: number) => {
  currId.value = id;
  currType.value = type;
  copyVisible.value = true;
};

const copyEmit = async (formData: any) => {
  if (currType.value === 1) {
    copy_1(formData);
  } else {
    copy_2(formData);
  }
};

// 模板查重函数
const validateName = async (name: string) => {
  try {
    if (name === currData.data.name && currData.data.id) {
      //
    } else {
      const data = {
        tType: currType.value,
        name
      };
      const res = await validateRules(RepeatSchemePeople, data);
      return Promise.resolve(res);
    }
  } catch (error: unknown) {
    console.log(error);
  }
};

const copy_1 = async (formData: any) => {
  const res: any = await GetBonboardingInformDetail({ id: currId.value });
  delete res.id;
  delete res.createdAt;
  res?.detail?.forEach((ele: any) => {
    delete ele.id;
    delete ele.hid;
  });
  res.required = 2;
  res.name = formData.name;
  await AddBonboardingInform(res);
  refresh_1();
};
const copy_2 = async (formData: any) => {
  const res: any = await GetBonboardingInformDetail({ id: currId.value });
  delete res.id;
  delete res.createdAt;
  res?.detail?.forEach((ele: any) => {
    delete ele.id;
    delete ele.hid;
  });
  res.required = 2;
  res.name = formData.name;
  await AddBonboardingInform(res);
  refresh_2();
};

// 复制弹窗点击确认并编辑
const copyEditEmit = (formData: any) => {
  if (currType.value === 1) {
    goEdit_1(currId.value, formData.name);
  } else {
    goEdit_2(currId.value, formData.name);
  }
};

// 修改启用状态
const changeEnable = async (record: any, type: 1 | 2) => {
  try {
    await EditBonboardingInformDefault({
      ids: [record.id],
      type,
      enable: record.enable as 1 | 2
    });
    if (type === 1) refresh_1();
    else refresh_2();
  } catch (error: unknown) {
    console.log(error);
  }
};

// 修改默认状态
const changeRequired = async (id: number, type: 1 | 2) => {
  try {
    await EditBonboardingInformDefault({
      id,
      type
    });
    if (type === 1) refresh_1();
    else refresh_2();
  } catch (error: unknown) {
    console.log(error);
  }
};

const refresh_2 = () => {
  data.value = {};
  tableRef_2.value.loadData();
};
const refresh_1 = () => {
  tableRef_1.value.loadData();
};
const visible = ref(false);
// 搜索
const search_1 = () => {
  refresh_1();
};
// 搜索
const search_2 = () => {
  refresh_2();
};
</script>
<style lang="less" scoped>
:deep(.w-e-toolbar) {
  display: none !important;
}
:deep(.w-e-text-container) {
  border: none !important;
}

.arco-space {
  display: flex;
  justify-content: space-between;
  padding: 20px;
  margin-right: 20px;
}

:deep(.look-one) {
  background-color: aqua;
}
#look-one {
  background-color: aqua;
}
.close {
  position: absolute;
  top: 18px;
  right: 30px;
  cursor: pointer;
}
.round {
  position: absolute;
  width: 50px;
  height: 50px;
  border: 4px solid #e4e4e4;
  border-radius: 50%;
  bottom: 10px;
  right: 50%;
  transform: translate(28px, 0px);
}

.enable::before {
  content: '';
  display: inline-block;
  width: 5px;
  height: 5px;
  border-radius: 50%;
  position: relative;
  right: 3px;
  background-color: var(--enable);
}
</style>
